/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3log.
 *
 * e3log is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3log is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3log. If not, see <https://www.gnu.org/licenses/>.
 */

package e3log

import (
	"fmt"
	"github.com/fatih/color"
	"io"
	"os"
)

func NewConsoleWriter(out io.Writer) *ConsoleWriter {
	isDiscard := out == io.Discard
	if !isDiscard {
		if file, ok := out.(*os.File); !ok || !(file == os.Stdout || file == os.Stderr) {
			panic("ConsoleWriter only supports os.Stdout, os.Stderr, io.Discard")
		}
	}

	writer := ConsoleWriter{
		out:       out,
		noColor:   false,
		easyRead:  true,
		isDiscard: isDiscard,
	}
	return &writer
}

type ConsoleWriter struct {
	out       io.Writer
	noColor   bool
	easyRead  bool
	isDiscard bool
}

func (ts *ConsoleWriter) SetNoColor(noColor bool) {
	ts.noColor = noColor
}

func (ts *ConsoleWriter) SetEasyRead(ok bool) {
	ts.easyRead = ok
}

func (ts *ConsoleWriter) write(level Level, cl *color.Color, bs []byte) {
	if !ts.isDiscard {
		if ts.easyRead {
			s := consoleEasyRead(level, cl, bs, ts.noColor)
			_, _ = fmt.Fprintf(ts.out, s)
		} else {
			s := logBytesToString(bs)
			if ts.noColor {
				_, _ = fmt.Fprintf(ts.out, s)
			} else {
				if cl == nil {
					_, _ = gLevelColors[level].Fprint(ts.out, s)
				} else {
					_, _ = cl.Fprint(ts.out, s)
				}
			}
		}
	}
}

func (ts *ConsoleWriter) sync() {
	// ConsoleWriter 不需要同步操作
}
